<?php
namespace plugins\setting\controller;

use cmf\controller\PluginAdminBaseController;//引入此类
use think\Db;
use think\Validate;
use plugins\setting\model\SettingModel;
use plugins\setting\model\SettingInfoModel;
use think\View;
use plugins\setting\lib\Setting;

/**
 * 设置类
 */
class SettingController extends PluginAdminBaseController
{
	protected $setting = null;
	protected function _initialize()
	{
		parent::_initialize();
		$this->setting = new Setting();
	}
	/**
	 * 设置页面
	 */
	public function index()
	{
		$list = Setting::getCache();
		return $this->fetch( 'setting/index' , [ 
			'list' => $list,
		] );
	}

	/**
	 * 更新设置信息
	 */
	public function updateSetting()
	{
		$this->setting->settingToDb() ;
		return api_json_echo( true , '更新成功' );
	}

	/**
	 * 更新缓存
	 */
	public function updateCache()
	{
		if( !$this->setting->updateCache() ){
			return api_json_echo( false , '更新失败' );
		}
		return api_json_echo( true , '更新成功' );
	}

	/**
	 * 切换页面
	 */
	public function changePage()
	{
		$param = $this->request->param();

		$validate = new Validate( [ [ 'name' , 'require' , '标识不能为空' ] ] );
		if( !$validate->check( $param ) ){
			return api_json_echo( false , $validate->getError() );
		}
		$name = $param [ 'name' ];
		$info = $this->setting->getCache( $name );
		if( !$info ){
			return api_json_echo( false , '配置项未查询到' );
		}
		try {
			$this->view->config( [
			 	'view_path' => PLUGINS_PATH."$name/view/",
			 	'view_base' => PLUGINS_PATH."$name/view/",
			 ] );
			$this->view->assign( [
				'config' => $info [ 'data' ]
			] );
			if( empty( $info [ 'template' ] ) ){
				throw new \Exception( "未设置模板信息,数据无法显示" );
			}
			$html = $this->view->fetch( $info[ 'template' ] );

		} catch (\Exception $e) {
			return '异常信息:'. $e->getMessage();
		}
		
		//创建页面
		return $html;
	}

	//保存设置
	public function saveSetting()
	{
		if( $this->request->isPost() ){
			$param['name'] = input( 'param.name' ) ;
			$param['data'] = input( 'param.data/a' );
			$validate = new Validate([
				[ 'name' , 'require' , '模块名不能为空' ]
			]);
			if( empty( $param [ 'data' ] ) ){
				return api_json_echo( false , '数据不能为空' );
			}
			if( !$validate->check( $param ) ){
				return api_json_echo( false , $validate->getError() );
			}

			$setting = SettingModel::get( [ 'name' => cmf_parse_name( $param [ 'name' ] ) ] );
			if( !$setting ){
				return api_json_echo( false , '配置不存在,请添加配置' );
			}

			$data = json_encode( $param [ 'data' ] , JSON_UNESCAPED_UNICODE );

			if( !SettingModel::where( 'name' , $param [ 'name' ] )->update( [ 'data' => $data ] ) ){
				return api_json_echo( false , '配置保存失败' );
			}
			//保存成功更新缓存
			$this->setting->updateCache();

			return api_json_echo( true , '配置保存成功' );
		}else{
			return api_json_echo( false , '非法请求' );
		}
	}

}